package com.dhh.util.manager;

import java.util.List;
import com.dhh.dao.DataBaseHelper;
import com.dhh.dao.GoalDAO;
import com.dhh.dao.WeightDAO;
import com.dhh.util.CUtil;
import com.dhh.vo.Goal;
import com.dhh.vo.Weight;

public class WeightManager {
	private WeightDAO dao;
	private GoalDAO gdao;
	private PlanManager pManager;
	
	public WeightManager(DataBaseHelper db){
		gdao = new GoalDAO(db);
		dao = new WeightDAO(db);
		pManager = new PlanManager(db);
	}
	
	public Weight getCurrentWeight(){
		return dao.getCurrentWeight();
	}
	
	public String getTotalGain(){
		double sw = Double.parseDouble(dao.getInitWeight().getWeight());
		double nw = Double.parseDouble(dao.getCurrentWeight().getWeight());
		return CUtil.formatNum(nw-sw);
	}
	
	public String getTodayGain(){
		Weight now = dao.getCurrentWeight();
		double cw = Double.parseDouble(now.getWeight());
		Weight next = dao.getWeightById(String.valueOf(Integer.parseInt(now.getId())-1));
		double nw = cw;
		if(next.getId()!=null)
			nw = Double.parseDouble(next.getWeight());		
		return CUtil.formatNum(cw-nw);
	}
	
	public List<Weight> getChartData(int limit){
		return dao.getlastWeight(limit);
	}
	
	public List<Weight> getWeightLog(){
		return dao.getWeightLogs(0);
	}
	
	public boolean addWeight(Weight w){
		Weight ew = dao.getWeightLog(w.getDate());
		if(ew.getId()!=null)
			dao.deleteWeightLog(ew.getId());
		
		return dao.addWeight(w);
	}
	
	public boolean addWeightGoal(Weight w){
		addWeight(w);
		
		Goal goal = gdao.getLastUpdateGoal();
		double sw = Double.valueOf(goal.getWeight());
		double way = Double.valueOf(goal.getWayGain());
		double cw = Double.valueOf(w.getWeight());
		if((sw+way)<=cw){
			Goal ng = new Goal();
			ng.setWayGain(goal.getWayGain());
			ng.setActivityLevel(goal.getActivityLevel());
			ng.setAge(goal.getAge());
			ng.setGender(goal.getGender());
			ng.setHeight(goal.getHeight());
			ng.setTargetWeight(goal.getTargetWeight());
			ng.setWeight(w.getWeight());
			gdao.addGoal(ng);
			pManager.addPlan(gdao.getLastUpdateGoal());
		}
		
		return true;
	}
	
	public boolean removeWeight(String id){
		return dao.deleteWeightLog(id);
	}
	
	public Weight getWeightLog(String date){
		return dao.getWeightLog(date);
	}
}
